/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package db;

import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import models.Employee;
import common.Md5;

/**
 *
 * @author pelle
 */
public class LoginDb extends AbstractDb implements LoginInterface {

    private int id;
    private String username = "";
    private String password = "";
    private String name = "";

    public Employee getLoginEmployee(String username, String password) {
        Employee emp = null;
        if(this.getLoginDetails(username, password)) {
            emp = new Employee(this.id, this.username, this.name);
        }

        return emp;
    }

    private boolean getLoginDetails(String username, String password) {
        boolean success = false;
        try {
            String md5Password = Md5.md5(password);
            ResultSet result = this.db.query("SELECT TOP 1 employee_id, employee_username, employee_password, employee_name FROM Employee WHERE employee_username = '" + username + "'");

            if(result != null && result.next()) {
                // MD5 password matchup!
                if(md5Password.equals(result.getString("employee_password"))) {
                    
                    this.id = result.getInt("employee_id");
                    this.username = result.getString("employee_username");
                    this.name = result.getString("employee_name");

                    success = true;
                }
            }

        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(LoginDb.class.getName()).log(Level.SEVERE, null, ex);
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(LoginDb.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(LoginDb.class.getName()).log(Level.SEVERE, null, ex);
        }

        return success;
    }

    private boolean transactionExample(String str, int id) {
        boolean success = false;
        if(this.newTransaction()) {

            this.addStatement("UPDATE blah (yaktaj) VALUES ('" + str + "') WHERE id = 2;");
            this.addStatement("UPDATE hihi (nana, thisid, lala) VALUES ('diller', " + id + ", '" + str + "');");

            if(this.getStatementCount() == 2) {
                success = commitTransaction();
            } else {
                this.rollbackTransaction();
            }
            
        }
        
        return success;
    }
    
    
}
